/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) RecordStatus.java 2018-08-06 11:56
 */

package cn.jh.common.core.domain;

import cn.jh.common.core.i18n.I18n;
import com.fasterxml.jackson.annotation.JsonValue;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;

import java.util.Locale;


/**
 * 表示记录（条目）的状态枚举。
 *
 * @author Fuchun
 * @since 1.0
 */
public enum RecordStatus implements EnumValue<Short>, TextValue<String, Short> {

    /** 表示记录已被逻辑删除。“已删除” */
    DELETED(-1, "record.status.deleted", "\u5df2\u5220\u9664"),

    /** 表示记录刚刚被创建（有的记录需要确认才会转为 {@link #NORMAL}）。“初始状态” */
    INITIAL(0, "record.status.initial", "\u521d\u59cb\u72b6\u6001"),

    /** 表示记录状态正常。“正常” */
    NORMAL(1, "record.status.normal", "\u6b63\u5e38"),

    /** 表示记录已被锁定（一般表现为只读状态）。“被锁定” */
    LOCKED(2, "record.status.locked", "\u88ab\u9501\u5b9a"),
    ;

    final short value;
    final String i18nCode;
    final String defaultText;

    RecordStatus(int value, String i18nCode, String defaultText) {
        this.value = (short) value;
        this.i18nCode = i18nCode;
        this.defaultText = defaultText;
    }

    @Contract(pure = true)
    @Override
    public String getText() {
        return getText(Locale.getDefault());
    }

    @Contract(pure = true)
    @Override
    @JsonValue
    public Short getValue() {
        return value;
    }

    @Contract(pure = true)
    public String getI18nCode() {
        return i18nCode;
    }

    @Contract(pure = true)
    public String getDefaultText() {
        return defaultText;
    }

    public String getText(Locale locale) {
        return I18n.getOrDefault(i18nCode, null, locale, defaultText);
    }

    @Nullable
    public static <N extends Number> RecordStatus of(N num) {
        return of(num, null);
    }

    @Contract("null, _ -> param2")
    public static <N extends Number> RecordStatus of(N num, RecordStatus defaultStatus) {
        if (num == null) return defaultStatus;
        short v = num.shortValue();
        switch (v) {
            case -1: return DELETED;
            case 0: return INITIAL;
            case 1: return NORMAL;
            case 2: return LOCKED;
            default: return defaultStatus;
        }
    }

    @Nullable
    public static RecordStatus forString(String input) {
        return forString(input, null);
    }

    @Contract("null, _ -> param2")
    public static RecordStatus forString(String input, RecordStatus defaultStatus) {
        String n;
        if (input == null || (n = input.trim().toUpperCase()).isEmpty()) {
            return defaultStatus;
        }
        switch (n) {
            case "DELETED": return DELETED;
            case "INITIAL": return INITIAL;
            case "NORMAL": return NORMAL;
            case "LOCKED": return LOCKED;
            default:
                return defaultStatus;
        }
    }
}
